package kr.saeildamil.androidStudy_second.brservice;

import kr.saeildamil.androidStudy_second.R;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;

public class MessangerServiceTest extends Activity {
	Messenger mService;
	boolean mBound;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch29and30_messengerservicetest);
	}

	@Override
	protected void onResume() {
		super.onStart();
		bindService(new Intent(this, MessengerService.class), mConn,
				Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onPause() {
		super.onStop();
		if (mBound) {
			unbindService(mConn);
			mBound = false;
		}
	}

	private ServiceConnection mConn = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mService = null;
			mBound = true;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mService = new Messenger(service);
			mBound = true;
		}
	};

	public void mOnClick(View v) {
		if (!mBound)
			return;
		Message msg = Message
				.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
		try {
			mService.send(msg);
		} catch (RemoteException e) {
			e.printStackTrace();
		}

	}
}
